package servlets;

import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import dataTypes.userDevice;


public class C2DMSendMessage implements Serializable{

	private static final String GOOGLELOGINADDRESS = "https://android.apis.google.com/c2dm/send";

	private static void sendMessage(userDevice user){
		try {
			StringBuilder dataToSend = new StringBuilder();
			dataToSend.append("registration_id=").append(URLEncoder.encode(user.getDeviceRegistrationID(), "UTF-8"));
			dataToSend.append("&collapse_key=").append(URLEncoder.encode("replace-existing", "UTF-8"));

			byte[] dataToSendByte = dataToSend.toString().getBytes("UTF-8");

			URL url = new URL(GOOGLELOGINADDRESS);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Authorization", "GoogleLogin auth=" + appManager.getInstance().getAuthToken());

			OutputStream out = conn.getOutputStream();
			out.write(dataToSendByte);
			out.close();
			
			int responseCode = conn.getResponseCode();
			if (responseCode == HttpServletResponse.SC_UNAUTHORIZED ||
		                responseCode == HttpServletResponse.SC_FORBIDDEN) { 
				//error
			 }
			
			if (responseCode == HttpServletResponse.SC_OK){
				String responseMessage = conn.getResponseMessage();
				if (responseMessage.contains("Error")){
					//TODO - All The dick if we get here...
				}
				else {
					//TODO - maybe to return True?
				}
			}			
		}
		catch (Exception e) {
			// TODO Autos-generated catch block
			e.printStackTrace();
		}
	}	
	
	static void sendMessageToAll(){		
		List<userDevice> users = appManager.getInstance().getUsers();
		for (userDevice usr :users) {
			if (!usr.getGoogleName().equals("OURACCOUNT"))
				sendMessage(usr);
		}		
	}	
}